package com.java1234.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.java1234.entity.Group;
import com.java1234.entity.MemberShip;
import com.java1234.entity.PageBean;
import com.java1234.entity.User;
import com.java1234.service.GroupService;
import com.java1234.service.MemberShipService;
import com.java1234.util.ResponseUtil;
import com.java1234.util.StringUtil;
import com.sun.deploy.net.HttpResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.java1234.service.UserService;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;
	@Autowired
	private MemberShipService memberShipService;
	@Resource
	private GroupService groupService;
	/**
	 * 用户登陆
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response) throws Exception{

		String userName  = request.getParameter("userName");
		String password  = request.getParameter("password");
		String groupId  = request.getParameter("groupId");
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("userName",userName);
		map.put("password",password);
		map.put("groupId",groupId);

		MemberShip memberShip = memberShipService.login(map);
		JSONObject result = new JSONObject();
		if (memberShip==null){
			result.put("success",false);
			result.put("errorInfo","用户名或密码错误");
		}else{
			result.put("success",true);
			request.getSession().setAttribute("currentMemberShip",memberShip);
		}

		ResponseUtil.write(response,result);

		return null;

	}


	/**
	 * 根据条件分页查询用户集合
	 * @param page
	 * @param rows
	 * @param s_user
	 * @return
	 */
	@RequestMapping("/list")
	public String list(@RequestParam(value = "page",required = false)String page, @RequestParam(value = "rows",required = false)String rows,
					   User s_user,HttpServletResponse response)throws Exception{

		PageBean pageBean = new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("id", StringUtil.formatLike(s_user.getId())); //查询用户名获取
		map.put("start",pageBean.getStart());
		map.put("size",pageBean.getPageSize());
		List<User> users = userService.find(map);
		Long total=userService.getTotal(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(users);
		result.put("rows",jsonArray);
		result.put("total",total);
		ResponseUtil.write(response,result);



		return null;
	}

	@RequestMapping("/delete")
	public String delete(@RequestParam(value = "ids",required = false)String ids,HttpServletResponse response) throws Exception{
		String [] idsStr = ids.split(",");
		Arrays.asList(idsStr).forEach(item->{userService.delete(item);});

		JSONObject result = new JSONObject();
		result.put("success",true);
		ResponseUtil.write(response,result);


		return null;
	}

    /**
     * 添加或修改用户
     * @param user
     * @param response
     * @param flag
     * @return
     * @throws Exception
     */
	@RequestMapping("/save")
    public String save(User user,HttpServletResponse response,Integer flag) throws Exception{
	    int resultTotal = 0;
	    if (flag==1){
	        resultTotal = userService.add(user);
        }else{
	        resultTotal = userService.update(user);
        }

        JSONObject result = new JSONObject();
	    if (resultTotal>0){
	        result.put("success",true);
        }else{
	        result.put("success",false);
        }
        ResponseUtil.write(response,result);

	    return null;
    }

    @RequestMapping("/existUserName")
    public String exitUserName(String userName,HttpServletResponse response) throws Exception{
	    JSONObject result = new JSONObject();
	    if (userService.findById(userName)==null){
	        result.put("exist",false);
        }else{
	        result.put("exist",true);
        }
        ResponseUtil.write(response,result);
	    return null;
    }

    @RequestMapping("/listWithGroups")
	public String listWithGroups(@RequestParam(value="page",required=false)String page, @RequestParam(value="rows",required=false)String rows,
								 User s_user, HttpServletResponse response) throws Exception{
		PageBean pageBean = new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		Map<String,Object> map = new HashMap<>();
		map.put("id",StringUtil.formatLike(s_user.getId())); // 查询用户名获取% %
		map.put("start",pageBean.getStart());
		map.put("size",pageBean.getPageSize());
		List<User> users = userService.find(map);
		users.forEach(user -> {
			StringBuffer groups = new StringBuffer();
			List<Group> groupsList = groupService.findByUserId(user.getId());
			groupsList.forEach(group -> {
				groups.append(group.getName()+",");
			});
			if (groups.length()>0){
				user.setGroups(groups.deleteCharAt(groups.length()-1).toString());
			}else{
				user.setGroups(groups.toString());
			}
		});
		Long total = userService.getTotal(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(users);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);


		return null;
	}

	@RequestMapping("/modifyPassword")
	public String modifyPassword(String id,String newPassword,HttpServletResponse response) throws Exception{
		User user = new User();
		user.setId(id);
		user.setPassword(newPassword);
		JSONObject result = new JSONObject();
		int resultTotal = userService.update(user);
		if (resultTotal>0){
			result.put("success",true);
		}else{
			result.put("success",false);
		}
		ResponseUtil.write(response,result);
		return null;
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) throws Exception{
		session.invalidate();
		return "redirect:/login.jsp";
	}




}
